<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>进出库登记</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            text-align: center;
        }

        form {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="text"],
        input[type="date"],
        select,
        input[type="number"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        th,
        td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        #summaryTable {
            margin-top: 20px;
        }

        .error {
            color: red;
            margin-bottom: 10px;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>

<body>
    <h1>进出库登记</h1>
    <form id="registrationForm">
        <div class="error" id="errorMessage"></div>
        <label for="itemName">物品名称:</label>
        <input type="text" id="itemName" required placeholder="请输入物品名称">
        <label for="operationType">操作类型:</label>
        <select id="operationType">
            <option value="入库">入库</option>
            <option value="出库">出库</option>
        </select>
        <label for="quantity">数量:</label>
        <input type="number" id="quantity" required min="1" placeholder="请输入数量">
        <label for="date">日期:</label>
        <input type="date" id="date" required value="<?php echo date('Y-m-d'); ?>" placeholder="请选择日期">
        <label for="amount">金额:</label>
        <input type="number" id="amount" placeholder="请输入金额">
        <label for="remark">备注:</label>
        <input type="text" id="remark" placeholder="可选，输入备注信息">
        <button type="submit">登记</button>
    </form>
    <button onclick="exportToXLSX()">导出为 XLSX</button>
    <input type="file" id="importFile" accept=".xlsx" onchange="handleFileSelection()">
    <button id="confirmImportButton" onclick="importFromXLSX()" disabled>确认导入</button>
    <label for="monthFilter">按月份筛选:</label>
    <input type="month" id="monthFilter" onchange="filterByMonth()">
    <table id="recordTable">
        <thead>
            <tr>
                <th>物品名称</th>
                <th>操作类型</th>
                <th>数量</th>
                <th>日期</th>
                <th>月份</th>
                <th>金额</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 记录将在这里显示 -->
        </tbody>
    </table>
    <!-- 在记录表格下方添加分页控件 -->
    <div id="paginationControls" style="margin: 10px 0; text-align: center;"></div>
    <table id="summaryTable">
        <thead>
            <tr>
                <th>物品名称</th>
                <th>月份</th>
                <th>上月结余</th>
                <th>入库数量</th>
                <th>出库数量</th>
                <th>入库金额</th>
                <th>出库金额</th>
                <th>结余数量</th>
            </tr>
        </thead>
        <tbody>
            <!-- 汇总记录将在这里显示 -->
        </tbody>
    </table>

    <script>
        // 新增分页相关变量
        let currentPage = 1;
        const recordsPerPage = 10; // 每页显示10条记录

        const registrationForm = document.getElementById('registrationForm');
        const recordTable = document.getElementById('recordTable').getElementsByTagName('tbody')[0];
        const summaryTable = document.getElementById('summaryTable').getElementsByTagName('tbody')[0];
        const monthFilter = document.getElementById('monthFilter');
        const importFile = document.getElementById('importFile');
        const confirmImportButton = document.getElementById('confirmImportButton');
        const errorMessage = document.getElementById('errorMessage');
        let records = [];
        let selectedFile = null;
        const STORAGE_KEY = 'inventory_records';

        // 从 localStorage 中加载数据
        function loadRecordsFromStorage() {
            const storedData = localStorage.getItem(STORAGE_KEY);
            if (storedData) {
                records = JSON.parse(storedData);
                renderRecords();
                renderSummary();
            }
        }

        // 将数据保存到 localStorage
        function saveRecordsToStorage() {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
        }

        // 修改后的renderRecords函数
        function renderRecords() {
            console.log('开始渲染记录，记录数量:', records.length);
            recordTable.innerHTML = '';
            
            // 获取筛选后的记录
            const filterValue = monthFilter.value;
            const filteredRecords = filterValue ? 
                records.filter(record => record.month === filterValue) : 
                records;

            // 计算分页
            const startIndex = (currentPage - 1) * recordsPerPage;
            const endIndex = startIndex + recordsPerPage;
            const paginatedRecords = filteredRecords.slice(startIndex, endIndex);

            if (paginatedRecords.length === 0) {
                console.log('当前页无记录，不进行渲染');
                const row = recordTable.insertRow();
                const cell = row.insertCell(0);
                cell.colSpan = 8;
                cell.textContent = '暂无记录';
                renderPaginationControls(filteredRecords);
                return;
            }
            paginatedRecords.forEach((record, index) => {
                console.log('当前渲染记录:', record);
                const newRow = recordTable.insertRow();
                const cell1 = newRow.insertCell(0);
                const cell2 = newRow.insertCell(1);
                const cell3 = newRow.insertCell(2);
                const cell4 = newRow.insertCell(3);
                const cell5 = newRow.insertCell(4);
                const cell6 = newRow.insertCell(5);
                const cell7 = newRow.insertCell(6);
                const cell8 = newRow.insertCell(7);

                cell1.textContent = record.itemName || '';
                cell2.textContent = record.operationType || '';
                cell3.textContent = record.quantity || '';
                cell4.textContent = record.date || '';
                cell5.textContent = record.month || '';
                cell6.textContent = record.amount || '';
                cell7.textContent = record.remark || '';

                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.addEventListener('click', function () {
                    records.splice(index, 1);
                    renderRecords();
                    renderSummary();
                    saveRecordsToStorage();
                });
                cell8.appendChild(deleteButton);
            });

            renderPaginationControls(filteredRecords);
            console.log('记录渲染完成');
        }

        // 新增分页控件渲染函数
        function renderPaginationControls(filteredRecords) {
            const totalRecords = filteredRecords.length;
            const totalPages = Math.ceil(totalRecords / recordsPerPage);
            const controls = document.getElementById('paginationControls');
            controls.innerHTML = '';

            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            prevButton.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderRecords();
                }
            });
            controls.appendChild(prevButton);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.style.margin = '0 2px';
                pageButton.disabled = i === currentPage;
                pageButton.addEventListener('click', () => {
                    currentPage = i;
                    renderRecords();
                });
                controls.appendChild(pageButton);
            }

            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            nextButton.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    renderRecords();
                }
            });
            controls.appendChild(nextButton);

            // 添加页码信息
            const info = document.createElement('span');
            info.style.marginLeft = '10px';
            info.textContent = `共 ${totalRecords} 条记录，当前第 ${currentPage} 页`;
            controls.appendChild(info);
        }

        // 获取上一个月的月份
        function getPreviousMonth(month) {
            const [year, monthNum] = month.split('-').map(Number);
            let prevYear = year;
            let prevMonth = monthNum - 1;
            if (prevMonth === 0) {
                prevMonth = 12;
                prevYear--;
            }
            return `${prevYear}-${String(prevMonth).padStart(2, '0')}`;
        }

        function renderSummary() {
            console.log('开始渲染汇总信息，记录数量:', records.length);
            summaryTable.innerHTML = '';
            const filterValue = monthFilter.value;
            const filteredRecords = filterValue? records.filter(record => record.month === filterValue) : records;
            if (filteredRecords.length === 0) {
                console.log('筛选后记录数组为空，不进行汇总信息渲染');
                return;
            }
            const itemMonthlySummary = {};
            filteredRecords.forEach(record => {
                const itemName = record.itemName;
                const month = record.month;
                const key = `${itemName}-${month}`;
                if (!itemMonthlySummary[key]) {
                    itemMonthlySummary[key] = {
                        itemName: itemName,
                        month: month,
                        inQuantity: 0,
                        outQuantity: 0,
                        inAmount: 0,
                        outAmount: 0
                    };
                }
                if (record.operationType === '入库') {
                    itemMonthlySummary[key].inQuantity += parseInt(record.quantity) || 0;
                    itemMonthlySummary[key].inAmount += parseFloat(record.amount) || 0;
                } else {
                    itemMonthlySummary[key].outQuantity += parseInt(record.quantity) || 0;
                    itemMonthlySummary[key].outAmount += parseFloat(record.amount) || 0;
                }
            });

            for (const key in itemMonthlySummary) {
                const summary = itemMonthlySummary[key];
                const prevMonth = getPreviousMonth(summary.month);
                const prevMonthRecords = records.filter(record => record.itemName === summary.itemName && record.month === prevMonth);
                let prevMonthInQuantity = 0;
                let prevMonthOutQuantity = 0;
                prevMonthRecords.forEach(record => {
                    if (record.operationType === '入库') {
                        prevMonthInQuantity += parseInt(record.quantity) || 0;
                    } else {
                        prevMonthOutQuantity += parseInt(record.quantity) || 0;
                    }
                });
                const prevMonthBalance = prevMonthInQuantity - prevMonthOutQuantity;

                const balanceQuantity = prevMonthBalance + summary.inQuantity - summary.outQuantity;

                const newRow = summaryTable.insertRow();
                const cell1 = newRow.insertCell(0);
                const cell2 = newRow.insertCell(1);
                const cell3 = newRow.insertCell(2);
                const cell4 = newRow.insertCell(3);
                const cell5 = newRow.insertCell(4);
                const cell6 = newRow.insertCell(5);
                const cell7 = newRow.insertCell(6);
                const cell8 = newRow.insertCell(7);

                cell1.textContent = summary.itemName;
                cell2.textContent = summary.month;
                cell3.textContent = prevMonthBalance;
                cell4.textContent = summary.inQuantity;
                cell5.textContent = summary.outQuantity;
                cell6.textContent = summary.inAmount;
                cell7.textContent = summary.outAmount;
                cell8.textContent = balanceQuantity;
            }
            console.log('汇总信息渲染完成');
        }

        // 修改filterByMonth函数，重置页码
        function filterByMonth() {
            currentPage = 1; // 筛选时重置到第一页
            const filterValue = monthFilter.value;
            // 原有筛选逻辑...（保持原样）
            renderRecords();
            renderSummary();
        }

        function exportToXLSX() {
            const formattedRecords = records.map(record => ({
                物品名称: record.itemName,
                操作类型: record.operationType,
                数量: record.quantity,
                日期: record.date,
                月份: record.month,
                金额: record.amount,
                备注: record.remark
            }));
            const ws = XLSX.utils.json_to_sheet(formattedRecords);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Inventory Records');
            // 生成当前日期
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const dateString = `${year}-${month}-${day}`;
            // 文件名添加日期后缀
            const fileName = `inventory_records_${dateString}.xlsx`;
            XLSX.writeFile(wb, fileName, { bookType: 'xlsx', type: 'array' });
            alert('数据已成功导出为 XLSX 文件。');
        }

        function handleFileSelection() {
            selectedFile = importFile.files[0];
            if (selectedFile) {
                confirmImportButton.disabled = false;
            } else {
                confirmImportButton.disabled = true;
            }
        }

        function importFromXLSX() {
            if (!selectedFile) {
                alert('请选择一个 XLSX 文件进行导入。');
                return;
            }
            if (!selectedFile.name.endsWith('.xlsx')) {
                alert('请选择一个有效的 XLSX 文件。');
                importFile.value = '';
                confirmImportButton.disabled = true;
                selectedFile = null;
                return;
            }
            const reader = new FileReader();
            reader.onload = function (e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[firstSheetName];
                    const importedData = XLSX.utils.sheet_to_json(worksheet);
                    if (importedData.length === 0) {
                        alert('文件中没有有效数据，请检查。');
                        importFile.value = '';
                        confirmImportButton.disabled = true;
                        selectedFile = null;
                        return;
                    }
                    const expectedXlsxHeaders = ['物品名称', '操作类型', '数量', '日期', '月份', '金额', '备注'];
                    const expectedHeaders = ['itemName', 'operationType', 'quantity', 'date', 'month', 'amount', 'remark'];

                    // 创建中文到英文的表头映射
                    const headerMap = expectedXlsxHeaders.reduce((map, cnKey, index) => {
                        map[cnKey] = expectedHeaders[index];
                        return map;
                    }, {});

                    // 替换表头并转换数据
                    const headerKeys = Object.keys(headerMap); // 如 ['物品名称', '操作类型', ...]
                    const transformedData = importedData.map(record => {
                        const newRecord = {};
                        for (const cnKey of headerKeys) {
                            newRecord[headerMap[cnKey]] = record[cnKey];
                        }
                        return newRecord;
                    });
                    // 后续处理导入的数据-追加
                    // records = records.concat(transformedData);
                    // 替换合并操作为覆盖操作
                    records = transformedData;  // 修改此行
                    renderRecords();
                    renderSummary();
                    saveRecordsToStorage();
                    alert('数据导入成功，原有数据已清除。');  // 修改提示信息

                    importFile.value = '';
                    confirmImportButton.disabled = true;
                    selectedFile = null;
                } catch (error) {
                    alert('导入文件时出现错误，请检查文件格式。');
                    importFile.value = '';
                    confirmImportButton.disabled = true;
                    selectedFile = null;
                }
            };
            reader.readAsArrayBuffer(selectedFile);
        }

        registrationForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const itemName = document.getElementById('itemName').value;
            const operationType = document.getElementById('operationType').value;
            const quantity = document.getElementById('quantity').value;
            const date = document.getElementById('date').value;
            const amount = document.getElementById('amount').value;
            const remark = document.getElementById('remark').value;

            if (!itemName ||!quantity ||!date) {
                errorMessage.textContent = '请填写所有必填字段。';
                return;
            }

            if (parseInt(quantity) < 1) {
                errorMessage.textContent = '数量必须大于等于 1。';
                return;
            }

            if (parseFloat(amount) < 0) {
                errorMessage.textContent = '金额不能为负数。';
                return;
            }

            const month = date.slice(0, 7);
            const newRecord = {
                itemName,
                operationType,
                quantity,
                date,
                month,
                amount,
                remark
            };
            records.push(newRecord);
            renderRecords();
            renderSummary();
            saveRecordsToStorage();
            errorMessage.textContent = '';
            registrationForm.reset();
        });

        loadRecordsFromStorage();
    </script>
</body>

</html>